package JUC.comsumer10Producer2;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @className: ReaderWriterLockConPro
 * @Description:
 * @Author: wangyifei
 * @Date: 2022/9/7 16:05
 */
public class ReaderWriterLockConPro {
    private Queue<Integer> queue = new LinkedList<>();
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.ReadLock rlock = lock.readLock();
    private ReentrantReadWriteLock.WriteLock wlock = lock.writeLock();
    public void consume(){
        wlock.lock();
        try{
            if(queue.isEmpty()){

            }
            int i = queue.peek();
            System.out.println(Thread.currentThread().getName() + " consumer " + i);
        }finally {
            wlock.unlock();
        }
    }
    public void producer(){
        wlock.lock();
        try{
            int i = new Random().nextInt(100);
            queue.add(i);
            System.out.println(Thread.currentThread().getName() + " producer " + i);
        }finally {
            wlock.unlock();
        }
    }

    public static void main(String[] args) {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(15 , 15 , 1000 , TimeUnit.SECONDS
                ,new ArrayBlockingQueue<>(100));
        ReaderWriterLockConPro queue = new ReaderWriterLockConPro();
        for(int i = 0 ; i < 10 ; i++){
            pool.execute(()->{
                queue.consume();
            });
        }

        for(int i = 0 ; i < 5 ; i++){
            pool.execute(() -> {
                queue.producer();
            });
        }

    }
}
